package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final String[] notCheckUri = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",
            "/user/sendMsg",
            "/user/login"
    };

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    // 拦截请求之前的数据
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前请求
        String requestURI = request.getRequestURI();
        log.info("请求的uri： {}",requestURI);

        // 校验请求路径
        boolean checkFlag = check(requestURI);

        if (!checkFlag) {
            log.info("静态资源和登陆退出请求需要放行 url: {}", requestURI);
            return true;
        }

        // 判断当前是否登陆  --》 服务端
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录: uri: {}",requestURI);

            // 用户登陆，获取id值，将id值存入线程局部变量中
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);

            return true;
        }

        // 判断当前是否登陆  --》 移动端
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录: uri: {}",requestURI);

            // 用户登陆，获取id值，将id值存入线程局部变量中
            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);
            return true;
        }

        log.info("用户既没有登陆，也不是静态资源，需要拦截：uri: {}",requestURI);

        // 方式一：使用响应返回数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;


        // 方式二：因为拦截的都是ajax 请求，所以可以使用全局异常来处理
//        throw new LoginException("NOTLOGIN");
    }

    // 请求之后，视图渲染之前执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (BaseContext.getCurrentId() != null) {
            log.info("清除ThreadLocal中的数据，确保内存泄漏的发生");
            // 删除ThreadLocal中的数据，确保内存泄漏的发生
            BaseContext.removeCurrentId();
        }
    }

    private boolean check(String requestURI) {
        for (String uri : notCheckUri) {
            if (PATH_MATCHER.match(uri,requestURI)) {
                return false;
            }
        }
        return true;
    }
}
